<template>
  <div>
    <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="100px" class="form-style">
      <aside>Create or Update a Dictionary.</aside>
      <el-form-item label="Group" prop="dictGroup">
        <el-select v-model="form.dictGroup" filterable clearable class="filter-item" placeholder="Please select" @change="handleChange">
          <el-option v-for="item in dictGroups" :key="item.code" :label="item.text" :value="item.code" />
        </el-select>
        <el-button type="text" icon="el-icon-edit" @click="dialogFormVisible = true">Add Group</el-button>
      </el-form-item>
      <el-form-item label="Text" prop="text">
        <el-input v-model="form.text" clearable maxlength="64" show-word-limit />
      </el-form-item>
      <el-form-item label="Code" prop="code">
        <el-input v-model="form.code" clearable :placeholder="'The last code is ' + lastCode" maxlength="64" show-word-limit />
      </el-form-item>
      <el-form-item label="Text Color" prop="textColor">
        <el-color-picker v-model="form.textColor" />
      </el-form-item>
      <el-form-item label="Reserved1" prop="reserved1">
        <el-input v-model="form.reserved1" clearable maxlength="150" show-word-limit />
      </el-form-item>
      <el-form-item label="Reserved2" prop="reserved2">
        <el-input v-model="form.reserved2" clearable maxlength="150" show-word-limit />
      </el-form-item>
      <el-form-item label="Description" prop="description">
        <el-input v-model="form.description" :autosize="{ minRows: 3, maxRows: 5 }" type="textarea" placeholder="Please input" maxlength="255" show-word-limit />
      </el-form-item>
      <el-form-item>
        <el-button v-waves v-loading="loading" type="primary" @click="submitForm">Save Now</el-button>
        <el-button v-show="!isEdit" @click="reset">Reset</el-button>
        <span v-show="notSaved" style="margin-left: 10px; color: #E0640C;">Not Saved</span>
      </el-form-item>
    </el-form>

    <el-dialog v-el-drag-dialog title="Add Dictionary Group" :visible.sync="dialogFormVisible">
      <el-form ref="groupForm" :rules="rules" :model="groupForm" label-position="right" label-width="100px" class="form-style">
        <el-form-item label="Text" prop="text">
          <el-input v-model="groupForm.text" clearable maxlength="64" show-word-limit />
        </el-form-item>
        <el-form-item label="Code" prop="code">
          <el-input v-model="groupForm.code" clearable maxlength="64" show-word-limit />
        </el-form-item>
        <el-form-item label="Description" prop="description">
          <el-input v-model="groupForm.description" :autosize="{ minRows: 3, maxRows: 5 }" type="textarea" placeholder="please input" maxlength="255" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button v-loading="groupLoading" type="primary" @click="submitGroupForm">Save</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { fetchAll, createOrupdateDictionary } from '@/api/sys/dictionary'
import waves from '@/directive/waves' // waves directive
import elDragDialog from '@/directive/el-drag-dialog'

const defaultForm = {
  text: '',
  code: '',
  textColor: '#000000',
  dictGroup: '',
  description: '',
  reserved1: '',
  reserved2: ''
}
const defaultGroupForm = {
  text: '',
  code: '',
  textColor: '#000000',
  dictGroup: 'dict_group',
  description: ''
}

export default {
  name: 'Dictionary',
  directives: { waves, elDragDialog },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dictGroups: [],
      form: {}, // 表单
      initial: {}, // 表单初始值
      groupForm: {},
      rules: {
        text: [{ required: true, message: 'Text is required', trigger: 'blur' }],
        code: [{ required: true, message: 'Code is required', trigger: 'blur' }],
        dictGroup: [{ required: true, message: 'Dictionary Group is required', trigger: 'blur' }]
      },
      loading: false,
      groupLoading: false,
      dialogFormVisible: false,
      lastCode: '',
      notSaved: false // 保存状态
    }
  },
  computed: {
    ...mapGetters(['uid', 'dictionaries']),
    watchForm() {
      return Object.assign({}, this.form)
    }
  },
  watch: {
    watchForm: {
      handler: function(newVal, oldVal) {
        // 用JSON.stringify的方式对比对象内属性是否相等不严谨(顺序不一致会导致不相等)
        if (!(JSON.stringify(newVal) === JSON.stringify(this.initial))) {
          this.notSaved = true
        }
      },
      deep: true
    }
  },
  created() {
    if (this.isEdit) {
      const row = this.$route.params
      this.form = Object.assign({}, row, { dictGroup: row.dictGroup, uid: this.uid }, { createAt: undefined, modifyAt: undefined })
    } else {
      this.form = Object.assign({}, defaultForm)
    }
    this.groupForm = Object.assign({}, defaultGroupForm, { uid: this.uid })
    this.initial = Object.assign({}, this.form)
    this.fetchList()
  },
  methods: {
    fetchList() {
      fetchAll({ uid: 0, dictGroup: 'dict_group' }).then(response => {
        this.dictGroups = response.result
      })
    },
    handleChange(val) {
      const arr = this.dictionaries.filter(dict => dict.dictGroup === val)
      if (arr.length > 0) {
        this.lastCode = arr[arr.length - 1].code
      } else {
        this.lastCode = 'undefined'
      }
    },
    submitForm() {
      console.log(this.form)
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.loading = true
          createOrupdateDictionary(this.form)
            .then(response => {
              this.$notify({
                title: 'Success',
                message: 'save successfully',
                type: 'success',
                duration: 2000
              })
              if (!this.isEdit) {
                this.form = Object.assign({}, defaultForm)
                this.reset()
              }
              // 更新初始值
              this.initial = Object.assign({}, this.form)
              // 更新保存状态
              this.notSaved = false
              console.log(this.notSaved)
            })
            .catch(() => {
              this.loading = false
            })
          this.loading = false
        } else {
          return false
        }
      })
    },
    submitGroupForm() {
      console.log(this.groupForm)
      this.$refs.groupForm.validate(valid => {
        if (valid) {
          this.groupLoading = true
          createOrupdateDictionary(this.groupForm)
            .then(response => {
              this.$notify({
                title: 'Success',
                message: 'save successfully',
                type: 'success',
                duration: 2000
              })
              this.$store.dispatch('dictionary/setDictionaries', this.uid)
              this.$refs['groupForm'].resetFields()
              this.dialogFormVisible = false
            })
            .catch(() => {
              this.groupLoading = false
            })
          this.groupLoading = false
        } else {
          return false
        }
      })
    },
    reset() {
      this.$refs['dataForm'].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.form-style {
  margin-top: 1%;
  width: 88%;
  margin-left: 6%;
}
</style>
